<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-form ref="queryParams" :model="queryParams" size="small" :inline="true" v-show="showSearch"
          label-width="60px">
          <el-form-item label="项目">
            <!-- <el-input v-model="queryParams.title" placeholder="请输入内容" /> -->
            <el-select ref="selectRoom" v-model="capsuleInfoId" clearable placeholder="请选择太空舱基地" @change="onChange">
              <el-option v-for="(item ,index) in spaceRoomList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="queryParams.address" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="queryParams.phone" placeholder="请输入电话" maxlength="11" type="number" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.region" placeholder="请选择状态">
              <el-option label="在线" value="0"></el-option>
              <el-option label="离线" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker v-model="tiemValue" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitsear" icon="el-icon-search" size="mini">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 新增 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addSpace">新增</el-button>
          </el-col>
        </el-row>
      </el-col>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%" class="mb20">
        <el-table-column prop="title" label="项目" align="center">
        </el-table-column>
        <el-table-column prop="address" label="地址" align="center">
        </el-table-column>
        <el-table-column prop="manageName" label="姓名" width="90" align="center">
        </el-table-column>
        <el-table-column prop="managePhone" label="电话" align="center" width="120">
        </el-table-column>
        <el-table-column prop="lng" label="经度" align="center" width="110">
        </el-table-column>
        <el-table-column prop="lat" label="纬度" align="center" width="110">
        </el-table-column>
        <el-table-column prop="normalPrice" label="价格" align="center" width="80">
          <template slot-scope="scope">
            <div style="color: #e45656;">{{scope.row.normalPrice}}元</div>
          </template>
        </el-table-column>
        <el-table-column prop="realPrice" label="均价" align="center" width="80">
          <template slot-scope="scope">
            <div style="color: #e45656;">{{scope.row.realPrice}}元</div>
          </template>
        </el-table-column>
        <el-table-column label="封面" align="center" width="190">
          <template slot-scope="scope" style="display: flex;">
            <el-image class="img" v-for="(item ,index) in scope.row.imgs" :key="index" :src="item.url"
              :preview-src-list="imgList_" @click="choseEventImg(item.url)">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="capsuleTags" label="娱乐项目" align="center">
        </el-table-column>
        <el-table-column label="状态" align="center" width="60">
          <template slot-scope="scope">
            <div :style="{color:scope.row.status == 0 ? '#5ac725' : '#909399'}">{{scope.row.status == 0 ? '正常' : '停用'}}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="210" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-document"
              @click="handleDetail(scope.row.id , types = 'detail')">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit"
              @click="handleUpdate(scope.row.id , types = 'edit')">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
            <!-- <el-dropdown size="mini" @command="(command) => handleCommand(command, true)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handlePass" icon="el-icon-key">密码</el-dropdown-item>
                <el-dropdown-item command="handleCode" icon="el-icon-full-screen">二维码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background align='right' @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum" :page-size="queryParams.pageSize"
        layout="prev, pager, next" :total="total">
      </el-pagination>
    </el-row>
    <!-- 开始新增 -->
    <el-dialog :title="types == 'add'?'新增太空舱':(types == 'edit'?'编辑太空舱':'太空舱详情')" :visible.sync="dialogVisibles"
      width="40%" :before-close="handleClose">
      <el-form ref="addSpaceData" :model="addSpaceData" label-width="120px" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="基地名称" prop="title">
              <el-input v-model="addSpaceData.title" placeholder="请输入基地名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="酒店地址" prop="">
              <el-button type="primary" @click="showMapVisible = true"
                :disabled="types == 'add' || types =='edit' ? false : true ">酒店地址</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="经度" prop="lng">
              <el-input v-model="addSpaceData.lng" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="纬度" prop="lat">
              <el-input v-model="addSpaceData.lat" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="管理者姓名" prop="name">
              <el-input v-model="addSpaceData.name" placeholder="请输入基地管理者姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="管理者电话" prop="phone">
              <el-input type='number' v-model="addSpaceData.phone"
                placeholder="请输入基地管理者电话" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="酒店联系电话" prop="hotell_phone">
              <el-input v-model="addSpaceData.hotell_phone" placeholder="请输入酒店联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="正常消费价格" prop="hotell_price">
              <el-input v-model="addSpaceData.hotell_price" type="number" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="平均消费价格" prop="hotell_price_p">
              <el-input v-model="addSpaceData.hotell_price_p" type="number" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="基地设施" prop="hotell_facilities">
              <el-input v-model="addSpaceData.hotell_facilities" placeholder="项目设施多个请使用逗号隔开" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="酒店评分" prop="hotell_num">
              <el-input v-model="addSpaceData.hotell_num" type="number"
                oninput="if(value){value=value.replace(/[^\d]/g,1)} if(value<=0){value=1} if(value>10){value=5}"
                placeholder="请输评分" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="退房时间" prop="checkOutMaxNum">
              <el-input type="number"
                oninput="if(value){value=value.replace(/[^\d]/g,1)} if(value<=0){value=1} if(value>10){value=5}"
                v-model="addSpaceData.checkOutMaxNum" placeholder="请输入退房限定时间单位:分钟" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="分润点" prop="profit">
              <el-input type="number"
                oninput="if(value){value=value.replace(/[^\d]/g,1)} if(value<=0){value=''} if(value>100){value=100}"
                v-model="addSpaceData.profit" placeholder="请输入分润比例0--100" />
            </el-form-item>
          </el-col>
          <!-- 上传图片 -->
          <el-col>
            <el-form-item label="封面图片" prop="imgList" class="upLaods">
              <image-much-upload ref="fileUploadRefs" v-if="types == 'add' || types == 'edit'" :limit="4"
                :multiple="true" :disabled="!addDisabled" v-model="imgList" @handleRemove="handleRemove"
                @handleUploadSuccess="handleUploadSuccess" />
              <div v-else class="imgList">
                <img v-for="(item ,index) in imgList" :key="index" :src="item.url" alt="" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="酒店简介" prop="introduction">
              <el-input rows="4" v-model="addSpaceData.introduction" type="textarea" placeholder="请输入酒店简介"
                :clearable="true" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否启用" prop="hotell_status">
              <el-switch v-model="hotell_status" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="types == 'add' || types == 'edit'">
        <el-button @click="dialogVisibles = false">取 消</el-button>
        <el-button type="primary"
          @click="types == 'add' ? onSubmit('addSpaceData') : (types == 'detail'? '' : handleEdit_())">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 打开地图 -->
    <Map :dialogVisible="showMapVisible" />
  </div>
</template>

<script>
  import {
    FormItem
  } from 'element-ui'
  import {
    spaceList,
    spaceDetail,
    updateSpace,
    addSpace,
    editSpace
  } from '@/api/space/space'
  import {
    capsuleInfoSelects
  } from '@/api/space/spaceRoom'
  import ImageMuchUpload from "@/components/upload/upload"
  import Map from "@/components/map/index.vue"
  import json from 'highlight.js/lib/languages/json'
  export default {
    components: {
      Map,
      ImageMuchUpload
    },
    data() {
      return {
        addDisabled: false,
        imgList: [],
        imgList_: [],
        dialogImageUrl: '',
        id: '',
        types: 'add',
        tiemValue: '',
        // 上传图片
        uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload',
        fileList: [],
        file: [],
        headers: {
          "Authorization": ''
        },
        disabled: false,
        hotell_status: true,
        showMapVisible: false,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: '',
          name: '',
          phone: '',
          address: '',
          beginDate: '',
          endDate: '',
          region: ''
        },
        showSearch: true, // 显示搜索条件
        dialogVisibles: false,
        dialogVisible_img: false,
        dialogMap: false, // 打开地图
        tableData: [],
        addSpaceData: {
          title: '',
          name: '',
          phone: '',
          hotell_price: '',
          hotell_price_p: '',
          hotell_num: 5,
          introduction: '',
          hotell_phone: '',
          hotell_facilities: '',
          address: '',
          lng: '',
          lat: '',
          images: '',
          image_: '',
          checkOutMaxNum:5,
          profit:''
        },
        rules: {
          title: [{
            required: true,
            message: '请输入太空舱基地名称',
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: '请选择酒店地址',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入基地管理者姓名',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入基地管理者电话',
            trigger: 'blur'
          }],
          hotell_phone: [{
            required: true,
            message: '请输入酒店联系电话',
            trigger: 'blur'
          }],
          hotell_price: [{
            required: true,
            message: '请输入正常消费价格',
            trigger: 'blur'
          }],
          hotell_price_p: [{
            required: true,
            message: '请输入正平均消费价格',
            trigger: 'blur'
          }],
          hotell_num: [{
            required: true,
            message: '请输入酒店评分',
            trigger: 'blur'
          }],
          checkOutMaxNum: [{
            required: true,
            message: '退房时间在1至5分钟之间',
            trigger: 'blur',
            min: 1,
            max: 5
          }],
          hotell_facilities: [{
            required: true,
            message: '请输入基地项目如：烧烤，KTV，游泳等',
            trigger: 'blur'
          }],
        },
        times: '',
        capsuleInfoId:'',
        spaceRoomList: []
      }
    },
    created() {
      this.getspaceList()
      this.headers.Authorization = this.$store.getters.token
      capsuleInfoSelects().then(res => {
        this.spaceRoomList = res.data
      })
    },
    provide() {
      return {
        fatherSetPosition: this.setPosition,
      }
    },
    methods: {
      onChange(e){
        if(this.spaceRoomList.length > 0){
          this.spaceRoomList.forEach(item =>{
            if(item.value == e){
              this.queryParams.title = item.label
            }
          })
        }
      },
      // 新增
      addSpace() {
        this.types = 'add'
        this.addSpaceData = {}
        this.imgList = []
        this.$nextTick(() => {
          this.$refs.fileUploadRefs.$refs.UploadRef.clearFiles()
        })
        this.dialogVisibles = true
      },
      // 图片
      handleRemove(file, index) {
        this.imgList.forEach((item, ik) => {
          if (item == file.url) {
            this.$delete(this.imgList, ik)
          }
        })
        this.imgList.splice(index, 1)
        this.addSpaceData.images = JSON.stringify(this.imgList)
      },
      handleUploadSuccess(url) {
        this.imgList = this.imgList.concat(url)
        this.addSpaceData.images = JSON.stringify(this.imgList)
      },
      setPosition(position) {
        // console.log(position)
        this.addSpaceData.lng = position.longitude
        this.addSpaceData.lat = position.latitude
        this.addSpaceData.cityId = position.cityId
        this.addSpaceData.address = position.address
        this.showMapVisible = false
      },
      // 获取列表
      getspaceList() {
        this.loading = true;
        spaceList({
          // "areaId": 0,
          "createBeginTime": "",
          "createEndTime": "",
          "manageName": "",
          "pageNum": this.queryParams.pageNum,
          "pageSize": this.queryParams.pageSize,
          "status": 99,
          "title": ""
        }).then(res => {
          this.loading = false
          res.data.rows.forEach((item, key) => {
            this.$set(item, 'imgs', JSON.parse(item.imgs))
          })
          this.total = res.data.total
          this.tableData = res.data.rows
        })
      },
      addSpaces_(id) {
        editSpace({
          "address": this.addSpaceData.address,
          "areaId": this.addSpaceData.cityId,
          "capsuleDesc": this.addSpaceData.introduction, //基地描述
          "capsuleTags": this.addSpaceData.hotell_facilities, // 酒店标签
          "capsuleTel": this.addSpaceData.phone, // 酒店联系电话
          "imgs": JSON.stringify(this.imgList), // 封面
          "lat": this.addSpaceData.lat, // 纬度
          "lng": this.addSpaceData.lng, // 经度
          "manageName": this.addSpaceData.name, // 管理者名称
          "managePhone": this.addSpaceData.hotell_phone, // 管理者电话
          "normalPrice": this.addSpaceData.hotell_price, // 价格
          "realPrice": this.addSpaceData.hotell_price_p, // 平均价格
          "score": this.addSpaceData.hotell_num,
          "status": this.hotell_status ? 0 : 1,
          "title": this.addSpaceData.title, // 基地标题
          "checkOutMaxNum": this.addSpaceData.checkOutMaxNum,
          "id": !id ? null : id,
          "profit":this.addSpaceData.profit == "" ? 0 : this.addSpaceData.profit/100
        }).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.dialogVisibles = false
            this.getspaceList()
          }
        })
      },
      onSubmit(addSpaceData) {
        this.$refs[addSpaceData].validate((valid) => {
          if (valid) {
            if (this.addSpaceData.lat == '' || this.addSpaceData.lng == '') return this.$message({
              message: '请选择酒店地址经纬度',
              type: 'warning'
            })
            this.addSpaces_(false)
          } else {
            this.$message({
              message: '提交失败！',
              type: 'error'
            })
            return false
          }
        })
      },
      // 查询
      onSubmitsear() {
        if (this.tiemValue && this.tiemValue.length > 0) {
          this.queryParams.beginDate = this.tiemValue[0]
          this.queryParams.endDate = this.tiemValue[1]
        } else {
          this.queryParams.beginDate = ''
          this.queryParams.endDate = ''
        }
        spaceList({
          "createBeginTime": this.queryParams.beginDate,
          "createEndTime": this.queryParams.endDate,
          "manageName": this.queryParams.name,
          "pageNum": 1,
          "pageSize": 10,
          "status": this.queryParams.region ? this.queryParams.region : '99',
          "title": this.queryParams.title
        }).then(res => {
          res.data.rows.forEach((item, key) => {
            this.$set(item, 'imgs', JSON.parse(item.imgs))
          })
          this.tableData = res.data.rows
          this.total = res.data.total
        })
      },
      resetQuery() { // 刷新
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          title: '',
          name: '',
          phone: '',
          address: '',
          beginDate: '',
          endDate: '',
          region: ''
        }
        this.tiemValue = ''
        this.getspaceList()
      },
      handleSizeChange(val) {
        console.log("pagesize===>",val)
        this.queryParams.pageNum = val
        this.getspaceList()
      },
      handleCurrentChange(val) {
        console.log("change===>",val)
        this.queryParams.pageNum = val
        this.getspaceList()
      },
      // 详情
      handleDetail(id) {
        spaceDetail(id).then(res => {
          console.log(res)
          let data = res.data
          let img = JSON.parse(data.imgs)
          this.addSpaceData = {
            title: data.title,
            address: data.address,
            name: data.manageName,
            phone: data.capsuleTel,
            hotell_price: data.normalPrice,
            hotell_price_p: data.realPrice,
            hotell_num: data.score,
            introduction: data.capsuleDesc,
            hotell_phone: data.managePhone,
            hotell_facilities: data.capsuleTags,
            lng: data.lng,
            lat: data.lat,
            checkOutMaxNum: 5,
            cityId: data.areaId,
            profit:data.profit*100
          }
          this.imgList = img
          this.hotell_status = data.status == 0 ? true : false
          this.dialogVisibles = true
        })
      },
      // 确定编辑
      handleEdit_() {
        this.addSpaces_(this.id)
      },
      handlePass() {

      },
      handleCode() {

      },
      // 编辑
      handleUpdate(id) {
        this.id = id
        this.handleDetail(id)
      },
      handleDelete(id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateSpace(id).then(res => {
            // console.log("res---->",res)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getspaceList()
            } else {
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            }
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      },
      handlePass() {

      },
      handleCode() {

      },
      choseEventImg(url) {
        this.imgList_.push(url)
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handlePass":
            this.handlePass();
            break;
          case "handleCode":
            this.handleCode();
            break;
          default:
            break;
        }
      },
      // 新增关闭
      handleClose(done) {
        this.dialogVisibles = false
      },
    }
  }
</script>
<style>
  .el-dialog__body {
    padding-top: 0 !important;
  }

  .el-upload--picture-card {
    width: 110px;
    height: 110px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 110px;
    height: 110px;
  }

  .el-upload-list--picture-card .el-upload-list__item>div {
    width: 100%;
    height: 100%;
  }
</style>
<style lang="scss">
  .eluploader-icon {
    width: 80px;
    height: 80px;
    border: 1px dotted #cccccc;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
  }

  .avatar {
    width: 80px;
    height: 80px;
  }

  .img {
    cursor: pointer;
    width: 40px;
    height: 40px;
    margin-right: 4px;
  }

  .imgList {
    display: flex;
    align-items: center;

    // justify-content: space-around;
    // flex-wrap: wrap;
    img {
      width: 80px;
      height: 80px;
      margin-right: 4px;
      background: #f5f5f5;
      border-radius: 4px;
    }
  }
</style>
